/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.common;

import java.util.Map;

import com.jfinal.aop.Aop;
import com.jfinal.kit.LogKit;

import cn.hg.base.common.BaseConstants;
import cn.hg.jfsa.core.option.Options;
import cn.hg.jfsa.core.option.Options.OptionChangeListener;
import cn.hg.jfsa.core.service.OptionServiceApi;
import cn.hg.jfsa.web.theme.ThemeException;
import cn.hg.jfsa.web.theme.ThemeManager;

/**
 * @author Golly
 */
public class OptionInitializer implements OptionChangeListener {

	private static OptionInitializer me = new OptionInitializer();

	public static OptionInitializer me () {
		return OptionInitializer.me;
	}

	public void init () {
		Options.addListener(this);
		OptionServiceApi service = Aop.get(OptionServiceApi.class);
		Map<String, String> settingMap = service.getAll();

		for (String key : settingMap.keySet()) {
			Options.set(key, settingMap.get(key));
		}

	}

	@Override
	public void onChanged (String key, String newValue, String oldValue) {

		switch (key) {
			case BaseConstants.THEME_ID_NAME:
				this.initThemeManager(newValue);
				break;

			case JfsaConstants.ACTION_LOG_ENABLED:
				JfsaLogManager.me().setLogEnabled("true".equalsIgnoreCase(newValue));
				break;

			case JfsaConstants.ACTION_LOG_WRITE_LIMIT:
				JfsaLogManager.me().setLogLimit(new Integer(newValue));
				break;

			case JfsaConstants.ACTION_LOG_WRITE_TIME:
				JfsaLogManager.me().setLogTime(new Integer(newValue));
				break;
		}

	}

	private void initThemeManager (String themeId) {

		try {
			ThemeManager.me().setCurrentTheme(themeId);
		}
		catch (ThemeException e) {
			LogKit.error("主题 [" + themeId + "] 不存在！");
		}

	}

}
